﻿Imports Training.Common

Partial Public Class Quiz
    Inherits System.Web.UI.Page
    Dim qid As Integer ' quizid
    Dim qnm As String ' quizname

    ''' <summary>
    ''' Page Load event. Check for role and querystring data
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        

        If Not User.IsInRole("user") Then
            Response.Redirect("login.aspx")
        Else
            ' check for querystring data
            If Not IsNothing(Request.QueryString("qid")) And Not IsNothing(Request.QueryString("qnm")) Then
                qnm = Request.QueryString("qnm")
                ' load quiz title
                lblQuizTitle.Text = "Quiz for " & qnm

                ' set logo if available
                If Not IsNothing(Session("logo")) Then
                    imgLogo.Visible = True
                    imgLogo.ImageUrl = "images/logos/" & Session("logo")
                End If

                qid = Request.QueryString("qid")

                ' make sure user has NOT taken this quiz
                If CheckCompletedQuizForUser(Session("uid"), qid) Then
                    Response.Redirect("Training.aspx")
                End If

                ' load questions
                LoadQuestions(qid)
            Else
                ' redirect out
                Response.Redirect("Training.aspx")
            End If
        End If
    End Sub

    ''' <summary>
    ''' Clear the session on loguot
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Protected Sub LoginStatus2_LoggedOut(ByVal sender As Object, ByVal e As EventArgs)
        Session.Abandon()
    End Sub

    ''' <summary>
    ''' Load questions for Quiz
    ''' </summary>
    ''' <param name="qid"></param>
    ''' <remarks></remarks>
    Private Sub LoadQuestions(ByVal qid As Integer)
        rptQuestions.DataSource = GetQuizQuestionsByQuizID(qid)
        rptQuestions.DataBind()
    End Sub

    ''' <summary>
    ''' Get answers to questions user completed
    ''' </summary>
    ''' <param name="qid"></param>
    ''' <remarks></remarks>
    Private Sub GetAnswers(ByVal qid As Integer)
        Dim dt As New DataTable
        Dim dr As DataRow
        Dim i As Integer
        Dim blnAllAnswered As Boolean
        dt = GetQuizQuestionsByQuizID(qid)

        lblResult.Text = ""
        blnAllAnswered = True

        ' first pass, check for response to each question
        For Each dr In dt.Rows
            i = dr("QuestionID")
            Dim rb As RadioButtonList
            rb = rptQuestions.FindControl(i)
            If Len(rb.SelectedValue.ToString) = 0 Then
                lblResult.Text = "All Questions MUST be answered. <br />Question Missed: " & GetQuestionTextByQuestionID(i)
                blnAllAnswered = False
                Exit Sub
            End If
        Next

        ' if all questions were answered, insert
        If blnAllAnswered Then
            For Each dr In dt.Rows
                i = dr("QuestionID")
                Dim rb As RadioButtonList
                rb = rptQuestions.FindControl(i)
                InsertUserQuizQuestionResponse(Session("uid"), qid, i, CType(rb.SelectedValue.ToString, Integer), CheckUserQuestionResponse(i, CType(rb.SelectedValue.ToString, Integer)))
            Next
            ' mark quiz completed for user
            MarkQuizCompleteForUser(Session("uid"), qid, CheckUserQuizPassing(Session("uid"), qid))
            ' redirect back to Training Page
            'Response.Redirect("Training.aspx")

            ' display pass fail controls
            If CheckUserQuizPassing(Session("uid"), qid) Then
                iPass() ' passing
            Else
                iFail() ' failing
            End If
        End If

    End Sub

    ''' <summary>
    ''' Create RadioButtonList for question with answers
    ''' </summary>
    ''' <param name="qsd"></param>
    ''' <returns>RadioButtonList with AnswerID as value and Answer as Text</returns>
    ''' <remarks></remarks>
    Public Function CreateQuestionRBL(ByVal qsd As Integer) As String
        Dim rbl As New RadioButtonList

        rbl.ID = qsd
        rbl.DataSource = GetQuizQuestiionAnswersByQID(qsd, qid)
        rbl.DataValueField = "AnswerID"
        rbl.DataTextField = "Answer"
        rbl.DataBind()

        rptQuestions.Controls.Add(rbl)

        Return String.Empty
    End Function

    ''' <summary>
    ''' Complete Button click event
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks>Get all answers and record user responses</remarks>
    Private Sub btnComplete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnComplete.Click
        GetAnswers(qid)
    End Sub

    ''' <summary>
    ''' Cancel Button click event
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks>Do NOT record user responses to quiz, redirect back to training</remarks>
    Private Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Response.Redirect("Training.aspx")
    End Sub

    ''' <summary>
    ''' Display Question Image
    ''' </summary>
    ''' <param name="img"></param>
    ''' <returns>Returns string with image src and path</returns>
    ''' <remarks></remarks>
    Public Function ShowThumb(ByVal img, ByVal pos) As String
        Dim retVal As String

        If img Is DBNull.Value Then
            retVal = String.Empty
        Else
            If pos Is DBNull.Value Then
                retVal = "<a href=""javascript:void(0);"" onclick=""window.open('images/quizzes/full/" & img & "','_blank','menubar=0,location=0,scrollbars=1,resizable=1,width=350,height=480')""><img src=""images/quizzes/thumb/" & img & _
                    """ alt=""click image for larger view"" class=""imgTop"" /></a><br/>"
            Else
                If pos = 0 Then
                    retVal = "<a href=""javascript:void(0);"" onclick=""window.open('images/quizzes/full/" & img & "','_blank','menubar=0,location=0,scrollbars=1,resizable=1,width=350,height=480')""><img src=""images/quizzes/thumb/" & img & _
                        """ alt=""click image for larger view"" class=""imgRight"" /></a>"
                Else
                    retVal = "<a href=""javascript:void(0);"" onclick=""window.open('images/quizzes/full/" & img & "','_blank','menubar=0,location=0,scrollbars=1,resizable=1,width=350,height=480')""><img src=""images/quizzes/thumb/" & img & _
                        """ alt=""click image for larger view"" class=""imgTop"" /></a><br />"
                End If

            End If

        End If

        Return retVal
    End Function

    ''' <summary>
    ''' User Passed quiz, display congrats and button to
    ''' allow user to view and/or print their certificate
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub iPass()
        main.Visible = False
        interact.Visible = False
        postquiz.Visible = True
        hypRetake.Visible = False
        allQs.Visible = False
        acro.Visible = True
        Dim uVars As String
        uVars = "uid=" & Session("uid") & "&qid=" & qid

        lblPostMsg.Text = "<h1>Congratulations, you passed.</h1>Use the link below to View or Print your Certificate."

        hypCert.Target = "_blank"
        hypCert.NavigateUrl = "CertPrint.aspx?data=" & Server.UrlEncode(Encrypt(uVars))
    End Sub

    ''' <summary>
    ''' User Failed quiz, display message and instructions
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub iFail()
        main.Visible = False
        interact.Visible = False
        postquiz.Visible = True
        hypCert.Visible = False
        acro.Visible = False
        Dim uVars As String
        uVars = "qid=" & qid & "&qnm=" & qnm

        lblPostMsg.Text = "We're sorry, you missed too many questions to pass the quiz.<br />" & _
            "You did not receive a passing grade.<br />Click the link below to take the quiz again<br />" & _
            "or click &quot;Return to Training Page&quot; and view the training media again.<br />" & _
            "You will be able to retake the quiz from the training page."

        hypRetake.NavigateUrl = "RetakeQuiz.aspx?" & uVars

        ' show missed questions
        missing.Visible = True
        rptMissed.Visible = True
        MissedThese(Session("uid"), qid)
    End Sub

    ''' <summary>
    ''' load data for missed questions
    ''' </summary>
    ''' <param name="uid"></param>
    ''' <param name="qid"></param>
    ''' <remarks></remarks>
    Private Sub MissedThese(ByVal uid As Integer, ByVal qid As Integer)
        rptMissed.DataSource = MissedQuestions(uid, qid)
        rptMissed.DataBind()
    End Sub


    ' SHOOT ME NOW!
    '  ,--^----------,--------,-----,-------^--,
    '  | |||||||||   `--------'     |          O
    '  `+---------------------------^----------|
    '    `\_,-------, _________________________|
    '      / XXXXXX /`|     /
    '     / XXXXXX /  `\   /
    '    / XXXXXX /\______(
    '   / XXXXXX /
    '  / XXXXXX /
    ' (________(
    '  `------'
End Class